package ltd.dujiabao.cache_processor;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;

import com.alibaba.fastjson.JSON;

/**
 * @author : DuJiabao
 * @Project : cache_processor
 * @Time : 2022/1/15 11:01
 * @Desc :
 */
public class SinglePartProcessor implements Consumer<Path> {
    private final String outputDir;
    private static final String VIDEO_INFO_SUFFIX = ".info";
    private static final String VIDEO_SUFFIX = ".mp4";

    public SinglePartProcessor(String outputDir) {
        this.outputDir = outputDir;
        createIfAbsentDir(outputDir);
    }

    @Override
    public void accept(Path path) {
        try {
            accept(path, outputDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void createIfAbsentDir(String outputDir) {
        Path path = Paths.get(outputDir);
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void accept(Path inputPath, String outputDir) throws IOException {
        System.out.println("start to process " + inputPath + " video into " + outputDir);

        Optional<Path> infoPath = PathUtils.findFirstPathEndWiths(inputPath, VIDEO_INFO_SUFFIX);
        Optional<Path> video = PathUtils.findFirstPathEndWiths(inputPath, VIDEO_SUFFIX);
        if (!infoPath.isPresent() || !video.isPresent()) {
            return;
        }
        Optional<String> info = PathUtils.readFile(infoPath.get());
        if (!info.isPresent()) {
            return;
        }
        Map<String, String> map = JSON.parseObject(info.get(), Map.class);
        String videoName = map.get("PartName");
        if (StringUtils.isEmpty(videoName)) {
            return;
        }
        videoName = PathUtils.replaceAllIllegalChar(videoName);
        Path outputPath = Paths.get(outputDir, videoName + VIDEO_SUFFIX);
        Files.copy(video.get(), outputPath, StandardCopyOption.REPLACE_EXISTING);
        System.out.println("finish to process " + inputPath + " video to " + outputPath);
    }
}
